import React, { useEffect, useState } from 'react';
import { Row, Col, Card, Statistic, Progress, List, Avatar } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, UserOutlined, ShoppingOutlined, DollarOutlined, EyeOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { reportApi, monitorApi } from '@/services/api';
import type { SystemMetrics } from '@/types';

const Dashboard: React.FC = () => {
  const [systemMetrics, setSystemMetrics] = useState<SystemMetrics | null>(null);
  const [userStats, setUserStats] = useState<any>(null);
  const [paymentStats, setPaymentStats] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchAllData = async () => {
      setLoading(true);
      try {
        const dateRange = [
          new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          new Date().toISOString().split('T')[0]
        ];

        // Fetch user stats with error handling
        try {
          const userStatsResponse = await reportApi.getUserStats(dateRange);
          // 处理数据包装结构
          const userStats = {
            data: userStatsResponse.data || userStatsResponse
          };
          setUserStats(userStats);
        } catch (error) {
          console.error('Failed to fetch user stats:', error);
          // Set default data for user stats
          setUserStats({
            data: {
              totalUsers: 0,
              dates: [],
              values: []
            }
          });
        }

        // Fetch payment stats with error handling
        try {
          const paymentStatsResponse = await reportApi.getPaymentStats(dateRange);
          // 处理数据包装结构
          const paymentStats = {
            data: paymentStatsResponse.data || paymentStatsResponse
          };
          setPaymentStats(paymentStats);
        } catch (error) {
          console.error('Failed to fetch payment stats:', error);
          // Set default data for payment stats
          setPaymentStats({
            data: {
              totalRevenue: 0,
              todayOrders: 0,
              distribution: []
            }
          });
        }

        // Fetch system metrics with error handling
        try {
          const systemMetricsResponse = await monitorApi.getSystemMetrics();
          // 处理数据包装结构
          const systemMetrics = systemMetricsResponse.data || systemMetricsResponse;
          setSystemMetrics(systemMetrics);
        } catch (error) {
          console.error('Failed to fetch system metrics:', error);
          // Set default system metrics
          setSystemMetrics({
            cpu: 0,
            memory: 0,
            disk: 0,
            network: { in: 0, out: 0 }
          });
        }
      } catch (error) {
        console.error('Failed to fetch dashboard data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchAllData();
    const interval = setInterval(async () => {
      try {
        const response = await monitorApi.getSystemMetrics();
        const systemMetrics = response.data || response;
        setSystemMetrics(systemMetrics);
      } catch (error) {
        console.error('Failed to fetch system metrics:', error);
        // Don't show error messages for periodic updates
      }
    }, 30000);
    return () => clearInterval(interval);
  }, []);

  const getLineChartOption = () => ({
    title: {
      text: '用户增长趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: userStats?.data?.dates || []
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      name: '新增用户',
      type: 'line',
      data: userStats?.data?.values || [],
      smooth: true,
      itemStyle: {
        color: '#1890ff'
      }
    }]
  });

  const getPieChartOption = () => ({
    title: {
      text: '支付方式分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    series: [{
      type: 'pie',
      radius: '50%',
      data: paymentStats?.data?.distribution || [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  });

  const recentActivities = [
    { title: '用户 张三 完成了支付', time: '2 分钟前', avatar: 'https://joeschmoe.io/api/v1/random' },
    { title: '新用户 李四 注册成功', time: '5 分钟前', avatar: 'https://joeschmoe.io/api/v1/random' },
    { title: '订单 #12345 支付成功', time: '10 分钟前', avatar: 'https://joeschmoe.io/api/v1/random' },
    { title: '系统自动备份完成', time: '1 小时前', avatar: 'https://joeschmoe.io/api/v1/random' },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={userStats?.data?.totalUsers || 0}
              precision={0}
              valueStyle={{ color: '#3f8600' }}
              prefix={<UserOutlined />}
              suffix={<ArrowUpOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="今日订单"
              value={paymentStats?.data?.todayOrders || 0}
              precision={0}
              valueStyle={{ color: '#1890ff' }}
              prefix={<ShoppingOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总收入"
              value={paymentStats?.data?.totalRevenue || 0}
              precision={2}
              valueStyle={{ color: '#cf1322' }}
              prefix={<DollarOutlined />}
              suffix="¥"
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="今日访问"
              value={1234}
              precision={0}
              valueStyle={{ color: '#722ed1' }}
              prefix={<EyeOutlined />}
              suffix={<ArrowUpOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} lg={16}>
          <Card title="用户增长趋势" style={{ height: '400px' }}>
            <ReactECharts option={getLineChartOption()} style={{ height: '320px' }} />
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title="支付方式分布" style={{ height: '400px' }}>
            <ReactECharts option={getPieChartOption()} style={{ height: '320px' }} />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="系统监控">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <div>
                  <p>CPU 使用率</p>
                  <Progress 
                    percent={systemMetrics?.cpu || 0} 
                    status={systemMetrics?.cpu && systemMetrics.cpu > 80 ? 'exception' : 'active'} 
                  />
                </div>
              </Col>
              <Col span={12}>
                <div>
                  <p>内存使用率</p>
                  <Progress 
                    percent={systemMetrics?.memory || 0} 
                    status={systemMetrics?.memory && systemMetrics.memory > 85 ? 'exception' : 'active'} 
                  />
                </div>
              </Col>
              <Col span={12}>
                <div style={{ marginTop: '16px' }}>
                  <p>磁盘使用率</p>
                  <Progress 
                    percent={systemMetrics?.disk || 0} 
                    status={systemMetrics?.disk && systemMetrics.disk > 90 ? 'exception' : 'active'} 
                  />
                </div>
              </Col>
              <Col span={12}>
                <div style={{ marginTop: '16px' }}>
                  <p>网络流量</p>
                  <div style={{ fontSize: '12px', color: '#666' }}>
                    入: {systemMetrics?.network?.in || 0} MB/s<br />
                    出: {systemMetrics?.network?.out || 0} MB/s
                  </div>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="最近活动">
            <List
              itemLayout="horizontal"
              dataSource={recentActivities}
              renderItem={item => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Avatar src={item.avatar} />}
                    title={item.title}
                    description={item.time}
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;